package wangjg.android.wifiadmin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class StatusReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("onReceive", intent.getAction());

		if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
			BizModule.setAlarm(context);//启动定时广播
		}else{
			SharedPreferences pref = context.getSharedPreferences(Constant.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
	    	boolean enabled = pref.getBoolean("enabled", false);
	    	if(enabled){
	    		BizModule.sendServiceCmd(context, intent);	
	    	}
		}
	}
	
	public void onReceive1111111111(Context context, Intent intent) {
		Log.d("onReceive", intent.getAction());

		if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){
			this.onWifiStatusChange(context, intent);
		}
		
		if(intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)){
			this.onWifiRSSIChange(context, intent);
		}else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
			this.onNetStatusChange(context, intent);
		}

	}
	
	private void onNetStatusChange(Context context, Intent intent) {
		Log.d("WifiBroad_status", "网络状态已改变");
		NetworkInfo info = intent
				.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
		if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
			Log.d("WifiBroad_status", "wifi网络连接断开 ");
		}
		if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
			Log.d("WifiBroad_status", "连接到wifi网络");
		}	
	}

	private void onWifiRSSIChange(Context context, Intent intent) {
		// Wifi的连接速度及信号强度
		WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifiManager.getConnectionInfo();
		if (info.getBSSID() != null) {
			// 链接信号强度
			int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);
			// 链接速度
			int speed = info.getLinkSpeed();
			// 链接速度单位
			String units = WifiInfo.LINK_SPEED_UNITS;
			// Wifi源名称
			String ssid = info.getSSID();
		}
	}

	private void onWifiStatusChange(Context context, Intent intent) {
		int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
		if (wifistate == WifiManager.WIFI_STATE_DISABLED) {// 如果关闭
			Log.d("WifiBroad_status", "WIFI已禁用");
		}
		if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
			Log.d("WifiBroad_status", "WIFI启用");
		}
	}
}
